package com.vrv.netmgr.alarm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.GlobalConstants;
import com.vrv.common.UrlPrefix;
import com.vrv.common.listview.ListViewAdapter;
import com.vrv.common.listview.ListViewUtil;
import com.vrv.common.util.DateUtils;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.common.util.JsonUtil;
import com.vrv.netmgr.R;
import com.vrv.netmgr.alarm.detail.DetailMobileDevAuditActivity;
import com.vrv.netmgr.vo.SerializableMobileDevAudit;

/**
 * @Description 移动设备审计
 * @author gaopei
 * @date
 *
 */
@SuppressLint("HandlerLeak")
public class MobileDevAuditActivity extends Activity {

    // 存储数据的数组列表
    private ArrayList<HashMap<String, Object>> listData = new ArrayList<HashMap<String, Object>>();
    private ListView listView;
    private ListAdapter adapter = new ListAdapter();
    public String UNIT_NAME;
    public String DEP_NAME;
    public String USER_NAME;
    public String TEL;
    public String IP_ADDRESS;
    public String EVENT_TYPE;
    public String UDISK_ID;
    public String AUDIT_DESC;
    public String STRATEGY_NAME;
    public String LOGIN_USER;
    public String REPORT_TIME;
    public String CLIENT_TIME;
    public String MAC_ADDRESS;
    public int RECORD_COUNT;
    public int CUR_INDEX;
    /**
     * 等待对话框
     */
    private ProgressDialog progressDialog;
    // 通过点击按钮查询标记
    private boolean qryByBtnFlag = false;
    // 列表的页脚视图
    private View loadMoreView;
    // 异常判断标记
 	private boolean retVal;
    /**
     * 查询
     */
    private static final int BACK_NULL = 2;
    private static final int QUERY = 3;
    private static final int NET_ERR = 4;
    private static final int QUERY_BY_IP = 5;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.assets_list_page);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.common_title);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        init();
        progressDialog = ProgressDialog.show(MobileDevAuditActivity.this, "", "查询中...", true, true);

        new Thread(new Runnable() {
            @Override
            public void run() {
                getDataFromServer(0, false, null);
                if (!retVal){
					handler.sendEmptyMessage(NET_ERR);
				}else{
					if (null == listData || 0 == listData.size()) {
						handler.sendEmptyMessage(BACK_NULL);
					} else {
						handler.sendEmptyMessage(QUERY);
					}
				}
            }
        }).start();
    }

	/**listview背景设置*/
	private LinearLayout listBackView;
	
	/**
	 * 处理器
	 */
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            progressDialog.dismiss();
            switch (msg.what) {
            case QUERY:
                findViews();
				/** listview背景设置 */
				listBackView.setVisibility(listView.getVisibility());
				break;
            case QUERY_BY_IP:
                qryByBtnFlag = true;
                if (RECORD_COUNT > 0) {
                    listView.removeFooterView(loadMoreView);
                    listView.setVisibility(View.VISIBLE);
                    if (RECORD_COUNT > ListViewUtil.PAGESIZE) {
                        String deviceIP = msg.getData().getString("deviceIP");
                        loadMorePage(true, deviceIP);
                    }
                    initializeAdapter();
                    adapter.notifyDataSetChanged();
                } else
                    listView.setVisibility(View.GONE);
				/** listview背景设置 */
				listBackView.setVisibility(listView.getVisibility());
				break;
            case NET_ERR:
                Toast.makeText(MobileDevAuditActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
                onBackPressed();
                break;
            case BACK_NULL:
                Toast.makeText(MobileDevAuditActivity.this, "数据为空", Toast.LENGTH_LONG).show();
                onBackPressed();
                break;
            }
        }
    };

    private void init() {
        setTitle();
        IP_ADDRESS = this.getString(R.string.ip_address);
        EVENT_TYPE = this.getString(R.string.event_type);
        UNIT_NAME = this.getString(R.string.unit_name);
        DEP_NAME = this.getString(R.string.dep_name);
        TEL = this.getString(R.string.tel);
        USER_NAME = this.getString(R.string.userName);
        UDISK_ID = this.getString(R.string.udisk_id);
        AUDIT_DESC = this.getString(R.string.auditDesc);
        STRATEGY_NAME = this.getString(R.string.strategy_name);
        LOGIN_USER = this.getString(R.string.login_user);
        REPORT_TIME = this.getString(R.string.report_time);
        CLIENT_TIME = this.getString(R.string.client_time);
        MAC_ADDRESS = this.getString(R.string.macAddress);
        
		listBackView = (LinearLayout) findViewById(R.id.list_background);
    }

    /**
     * 查询所有数据
     *
     * @param pageNum
     */
    public void getDataFromServer(int pageNum, boolean byDeviceIP, String deviceIP) {

        /** 查询条件 */
        Map<String, String> map = new HashMap<String, String>();
        /** Map<String, Object> map = new HashMap<String, Object>(); */

        map.put(GlobalConstants.PAGE_NUM, pageNum + "");
        map.put(GlobalConstants.REG_ASSETS, GlobalConstants.ASSETS_REGISTERED + "");
        if (byDeviceIP)
            map.put(GlobalConstants.IP_ADDRESS, deviceIP);
        /** 查询结果 */
        retVal = qryMobileDevAudit(map);
    }

    public boolean qryMobileDevAudit(Map<String, String> map) {
        boolean retVal = false;
        HttpClientToServer httpClientToServer = new HttpClientToServer();
        String urlPrefix = new UrlPrefix(getApplicationContext()).getUrlPrefix();
        String urlAddr = urlPrefix + "/pmoveableDiskEvent/jsonList.do?auditTypeBigNum=1";
        String response = httpClientToServer.doPost(urlAddr, map);
        if (HttpClientToServer.DO_POST_ERR.equals(response) || HttpClientToServer.DO_POST_EXCEPT.equals(response))
            return retVal;
        try {
            JSONTokener jsonParser = new JSONTokener(response);
            JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
            retVal = jsonObj.getBoolean("success");
            if (!retVal)
                return retVal;
            int count = jsonObj.getInt("totalRecords");
            RECORD_COUNT = count;
            if (count < 1)
                return retVal;
            JSONArray jArr = jsonObj.getJSONArray("records");
            int jArrLen = jArr.length();
            if (jArrLen > 0)
                CUR_INDEX = Integer.parseInt(map.get(GlobalConstants.PAGE_NUM));
            for (int i = 0; i < jArr.length(); i++) {
                JSONObject jObj = (JSONObject) jArr.opt(i);
                HashMap<String, Object> myMap = new HashMap<String, Object>();
                myMap.put(UNIT_NAME, jObj.getString("unitName"));
                myMap.put(DEP_NAME, JsonUtil.getJsonString(jObj, "deptName"));
                myMap.put(USER_NAME, JsonUtil.getJsonString(jObj, "userName"));
                myMap.put(TEL, JsonUtil.getJsonString(jObj, "tel"));
                myMap.put(IP_ADDRESS, JsonUtil.getJsonString(jObj, "ipaddress"));
                myMap.put(EVENT_TYPE, JsonUtil.getJsonString(jObj, "auditTypeName"));
                myMap.put(UDISK_ID, JsonUtil.getJsonString(jObj, "reserved1"));
                myMap.put(AUDIT_DESC, JsonUtil.getJsonString(jObj, "description"));
                myMap.put(STRATEGY_NAME, JsonUtil.getJsonString(jObj, "policyName"));
                myMap.put(LOGIN_USER, JsonUtil.getJsonString(jObj, "authUserName"));
                myMap.put(REPORT_TIME, JsonUtil.getJsonString(jObj, "upTime"));
                myMap.put(CLIENT_TIME, JsonUtil.getJsonString(jObj, "clientTime"));
                myMap.put(MAC_ADDRESS, JsonUtil.getJsonString(jObj, "macAddress"));
                listData.add(myMap);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return retVal;
    }

    public void setTitle() {
        TextView title = (TextView) findViewById(R.id.title_text);
        title.setText("移动设备审计");

        /**
         * 返回按钮
         */
        ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
        backBtn.setVisibility(View.VISIBLE);
        backBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    public void findViews() {
        if (listView == null) {
            // 搜索输入框
            EditText edit = (EditText) findViewById(R.id.assets_conditionQry);
            // 搜索按钮
            ImageView search_btn = (ImageView) findViewById(R.id.search_go_btn);
            edit.setHint(R.string.input_device_ip);

            // /**查询条件添加事件*/
            // edit.addTextChangedListener(new MyTextWatcher(edit, search_btn));
            /** 查询按钮添加事件 */
            search_btn.setOnClickListener(new ClickSearchBtnListener(edit, search_btn));

            listView = (ListView) findViewById(R.id.assets_lv_id);
        }
        if (RECORD_COUNT > 0) {
            listView.removeFooterView(loadMoreView);
            listView.setVisibility(View.VISIBLE);
            if (RECORD_COUNT > ListViewUtil.PAGESIZE)
                loadMorePage(false, null);
            initializeAdapter();
            if (listView.getAdapter() == null)
                listView.setAdapter(adapter);
            else
                adapter.notifyDataSetChanged();
            listView.setOnItemClickListener(new ListViewItemClick());
        }
    }

    /**
     * 查询按钮事件处理
     *
     * @author zxb
     *
     */
    private class ClickSearchBtnListener implements View.OnClickListener {
        EditText edit;
        ImageView search_btn;

        ClickSearchBtnListener(EditText edit, ImageView search_btn) {
            this.edit = edit;
            this.search_btn = search_btn;
        }

        @Override
        public void onClick(View v) {
            final String editVal = edit.getText().toString();
            listData.clear();
            adapter.clear();
            progressDialog = ProgressDialog.show(MobileDevAuditActivity.this, "", "查询中...", true, true);
            search_btn.setEnabled(false);
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    getDataFromServer(0, true, editVal);
                    Message msg = new Message();
                    msg.what = QUERY_BY_IP;
                    Bundle data = new Bundle();
                    data.putString("deviceIP", editVal);
                    msg.setData(data);
                    handler.sendMessage(msg);
                    search_btn.setEnabled(true);
                }
            });
        }
    }

    /**
     * 初始化ListView的适配器
     */
    public void initializeAdapter() {

        for (int i = 0; i < listData.size(); i++)
            adapter.addItem(listData.get(i));
    }

    private class ListViewItemClick implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            HashMap<String, Object> hashMap = adapter.getData(arg2);
            //
            SerializableMobileDevAudit serializable = new SerializableMobileDevAudit();
            serializable.setUNIT_NAME(hashMap.get(UNIT_NAME).toString());
            serializable.setDEP_NAME(hashMap.get(DEP_NAME).toString());
            serializable.setUSER_NAME(hashMap.get(USER_NAME).toString());
            serializable.setTEL(hashMap.get(TEL).toString());
            serializable.setIP_ADDRESS(hashMap.get(IP_ADDRESS).toString());
            serializable.setEVENT_TYPE(hashMap.get(EVENT_TYPE).toString());
            serializable.setUDISK_ID(hashMap.get(UDISK_ID).toString());
            serializable.setAUDIT_DESC(hashMap.get(AUDIT_DESC).toString());
            serializable.setSTRATEGY_NAME(hashMap.get(STRATEGY_NAME).toString());
            serializable.setLOGIN_USER(hashMap.get(LOGIN_USER).toString());
            serializable.setREPORT_TIME(hashMap.get(REPORT_TIME).toString());
            serializable.setCLIENT_TIME(hashMap.get(CLIENT_TIME).toString());
            serializable.setMAC_ADDRESS(hashMap.get(MAC_ADDRESS).toString());
            //
            Intent intent = new Intent(MobileDevAuditActivity.this, DetailMobileDevAuditActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("info", serializable);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    public void loadMorePage(final boolean byDeviceIP, final String deviceIP) {
        loadMoreView = getLayoutInflater().inflate(R.layout.list_page_load, null);
        final Button loadNextButton = (Button) loadMoreView.findViewById(R.id.loadNextButton);
        final Button loadPreButton = (Button) loadMoreView.findViewById(R.id.loadPreButton);
        loadNextButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (loadNextButton.getText().equals("查看下一页")) {
                    loadNextButton.setText("正在加载中..."); // 设置按钮文字
                    loadNextButton.setEnabled(false);
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            loadMoreData(true, byDeviceIP, deviceIP);
                            adapter.notifyDataSetChanged();
                            loadNextButton.setText("查看下一页"); // 恢复按钮文字
                            if ((CUR_INDEX + 1) * ListViewUtil.PAGESIZE >= RECORD_COUNT)
                                loadNextButton.setVisibility(View.GONE);
                            if (CUR_INDEX == 1)
                                loadPreButton.setVisibility(View.VISIBLE);
                            loadNextButton.setEnabled(true);
                        }
                    }, 0);
                }
            }
        });
        loadPreButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (loadPreButton.getText().equals("查看上一页")) {
                    loadPreButton.setText("正在加载中..."); // 设置按钮文字
                    loadPreButton.setEnabled(false);
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            loadMoreData(false, byDeviceIP, deviceIP);
                            adapter.notifyDataSetChanged();
                            loadPreButton.setText("查看上一页"); // 恢复按钮文字
                            if (CUR_INDEX == 0)
                                loadPreButton.setVisibility(View.GONE);
                            if ((CUR_INDEX + 2) * ListViewUtil.PAGESIZE >= RECORD_COUNT)
                                loadNextButton.setVisibility(View.VISIBLE);
                            loadPreButton.setEnabled(true);
                        }
                    }, 0);
                }
            }
        });
        listView.addFooterView(loadMoreView); // 设置列表底部视图
    }

    /*
     * 加载更多数据
     */
    private void loadMoreData(boolean pageDown, boolean byDeviceIP, String deviceIP) {
        int index;
        if (pageDown)
            index = CUR_INDEX + 1;
        else
            index = CUR_INDEX - 1;
        listData.clear();
        adapter.clear();
        getDataFromServer(index, byDeviceIP, deviceIP);
        int datasize = listData.size();
        for (int i = 0; i < datasize; i++)
            adapter.addItem(listData.get(i));
    }

    private class ListAdapter extends ListViewAdapter {
        @Override
        public View getView(int position, View view, ViewGroup parent) {
            final HashMap<String, Object> hashMap = getData(position);
            if (view == null) {
                view = LayoutInflater.from(MobileDevAuditActivity.this).inflate(R.layout.mobiledevaudit_listpage_item, null);
            }
            /**默认背景色设置*/
			view.setBackgroundResource(R.drawable.list_item_state1);
			/**双行背景色设置*/
			if (position % 2 == 0) {
				view.setBackgroundResource(R.drawable.list_item_state);
			}
            TextView tv1 = (TextView) view.findViewById(R.id.tv_depname);
            TextView tv2 = (TextView) view.findViewById(R.id.tv_devip);
            TextView tv3 = (TextView) view.findViewById(R.id.tv_devname);
            tv1.setText(hashMap.get(IP_ADDRESS).toString());
            tv2.setText(hashMap.get(EVENT_TYPE).toString());
            tv3.setText(hashMap.get(REPORT_TIME).toString());
            return view;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
        super.onBackPressed();
    }
}
